package hibari.server.servlet;

import hibari.PMF;
import hibari.client.model.Music;
import hibari.server.model.ImageData;

import java.io.IOException;
import java.text.MessageFormat;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

/**
 * 이미지 아이디로 이미지를 얻는 서블릿.
 * 
 * @see ImageData
 * @see Music#getImageId()
 * 
 * @author Jeeeyul
 * 
 */
public class ImageView extends HttpServlet {
	private static final long serialVersionUID = -2596121872109826954L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setHeader("Cache-Control", "max-age=300");
		String id = req.getParameter("id");
		try {

			PersistenceManager pm = PMF.get().getPersistenceManager();
			Key key = KeyFactory.createKey("ImageData", Long.parseLong(id));
			ImageData m = pm.getObjectById(ImageData.class, key);
			if (m.getData() != null && m.getData().getBytes() != null && m.getData().getBytes().length > 0) {
				resp.setContentType(getMimeType(m));
				resp.setHeader("Content-Disposition",
						MessageFormat.format("Content-Disposition: attachment; filename={0}", m.getFilename()));
				resp.getOutputStream().write(m.getData().getBytes());
			} else {
				resp.sendRedirect("/images/no-image.jpg");
			}
		} catch (Exception e) {
			resp.sendRedirect("/images/no-image.jpg");
		}
	}

	private String getMimeType(ImageData imageData) {
		String filename = imageData.getFilename();
		int extensionOffset = filename.lastIndexOf(".");
		String extension = null;
		if (extensionOffset >= 0) {
			extension = filename.substring(extensionOffset + 1).toLowerCase();
		}
		if ("jpg".equals(extension) || "jpeg".equals(extension) || "jpe".equals(extension)) {
			return "image/jpeg";
		}
		if ("gif".equals(extension)) {
			return "image/gif";
		}
		if ("png".equals(extension)) {
			return "image/png";
		}

		return "image/jpeg";
	}

}
